let spuId;
let goodsBox
let sortWeightIdInfo = "sort-weight";
let frmSortWeightIdInfo = "frm-lose-weight";
let sortWeightId = sortWeightIdInfo;
//type:0:称重；1:报损
let sortTyp = 0;

$(document).ready(function () {

    initSortTable(null, null);
    packList();
    Cookies.remove('boxCode');
    Cookies.remove('checkWeight');
    $('[data-toggle="tooltip"]').tooltip();

    $("#select-id").selectpicker("refresh");
    //render方法强制重新渲染引导程序 - 选择ui,如果当您编程时更改任何相关值而影响元素布局，这将非常有用。
    $('#select-id').selectpicker('render');
    $(".selectpicker").on("changed.bs.select", function (e) {
        spuId = $(this).val();
    });

    //称重按钮
    $('#check-weight').on("click", function (e) {
        const input = $(this).val();
        checkWeight(input);
    });

    $("#sort-change-shifts").on("click", function (e) {
        sortChangeShifts();
    });

    // initSortTable(null, null);

    //报损显示弹窗
    $('#frm-lose-model').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        console.log(">>>>>>>>>>" + JSON.stringify(button));
        var recipient = button.data('whatever'); // 解析出data-whatever内容
        $('#frm-loss-button').removeAttr("disabled");
        if (recipient) {
            var modal = $(this);
            modal.find('.modal-title').text('Message To ' + recipient);
            modal.find('.modal-body input').val(recipient);
        }
    });

    //报损隐藏弹窗
    $('#frm-lose-model').on('hide.bs.modal', function (event) {
        console.log("隐藏》》》》》》》");
        $('#goods-detail-id').val("");
        $('#frm-lose-weight').val("");
        $('#frm-loss-button').removeAttr("disabled");
        $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);

        clearInterval(sortSetInterval);
        sortWeightId = sortWeightIdInfo;
        sortTyp = 0;
        sortWeightInfo('sort-spu-table', sortWeightId, sortTyp, 0, null, 0);
        const std = $('#sort-spu-table').bootstrapTable('getData');
        if (Array.isArray(std) && std.length > 0) {
            const objBox = std[0];
            $("#sort-weight").val(objBox.weight);
        }
    });

    //报损下拉
    // $('#frm-lose-select').selectpicker('render');
    $("#frm-lose-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-detail-id').val(temp);
    });

    //降级原料下拉
    // $('#frm-spu-select').selectpicker('render');
    $("#frm-spu-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });

    //降级等级下拉
    // $('#frm-spu-grade-select').selectpicker('render');
    $("#frm-spu-grade-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });

    //降级标准下拉
    /*$('#demotion-standard-select').selectpicker('render');
    $("#demotion-standard-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });*/

    //降级显示弹窗
    $('#frm-demotion-model').on('show.bs.modal', function (event) {
    });

    //降级隐藏弹窗
    $('#frm-demotion-model').on('hide.bs.modal', function (event) {
        $('#demotion-goods-detail-box-code').val("");
        $('#demotion-goods-detail-id').val("");
        $('#frm-spu-select').selectpicker('val', ['noneSelectedText']);
        $('#frm-spu-grade-select').selectpicker('val', ['noneSelectedText']);
        $('#demotion-standard-select').selectpicker('val', ['noneSelectedText']);
    });

    /*  $('#sort-spu-table').on('check.bs.table', function (e,row, $element) {
          console.log("选中的行："+JSON.stringify(row));
          $('#sort-spu-table').bootstrapTable('uncheckAll');
          $('#sort-spu-table').bootstrapTable('checkBy', {field: 'id', values:[row.id]});
      });*/

    sortWeightInfo('sort-spu-table', sortWeightId, sortTyp, 0, null, 0);
});


let packs;

/**
 * 获取包装袋列表
 */
function packList() {
    const opt = {};
    $.ajax({
        type: "POST",
        url: "/system/pack/sort/list",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.length > 0) {
                        packs = data.data;
                    } else {
                    }
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

/**
 * 包装袋select下拉列表
 */
function packsToSelect(value, row, index) {
    let selectHtml = '';
    if (packs && packs.length > 0) {
        let selectOptions = '';
        selectOptions += '<option>请选择</option>';
        for (let i = 0; i < packs.length; i++) {
            const pack = packs[i];
            console.log("packsToSelect:" + value + ";" + pack.id);
            if (value && value == pack.id) {
                selectOptions += '<option value="' + pack.id + '" selected>' + pack.name + '</option>';
            } else {
                selectOptions += '<option value="' + pack.id + '">' + pack.name + '</option>';
            }

        }
        selectHtml = '<select class="pack-select" onchange="changeClick(this,' + row.id + ',' + index + ')">' + selectOptions + '</select>';
    }
    return selectHtml;
}

function changeClick(obj, rowId, index) {
    $('#pack-select option').each(function () {
        //取消掉正在选中的
        $(this).attr("selected", false);
    });
    console.log("选择的包装袋：" + JSON.stringify(obj.value));
    $('#sort-spu-table').bootstrapTable('updateCell', {
        index: index,
        field: 'packId',
        value: obj.value
    });
    $('#pack-select').find("option[value='" + obj.value + "']").prop("selected", true);
}

//净重响应
function weighRespCallBack(obj, cancel, opt) {
    if (!obj) {
        return;
    }
    console.log("称重响应：" + JSON.stringify(obj));
    $('#check-weight').show();
    if (!cancel) {
        const data = obj.data;
        delResponseFromWcs(obj, opt);
        if (data.code == 0) {

        } else {
            BootstrapDialog.alert(data.msg);
        }
    }
}

//分拣称重
function sortWeightCallBack(obj, cancel, opt) {
    if (!obj) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(obj));
    if (!cancel) {
        delResponseFromWcs(obj, opt);
        const data = obj.data;
        if (data.code == 0) {
            const boxCode = data.boxCode;
            $('#spu-box-code').text(boxCode);
            $('#ware-box-code').val(boxCode);
            $('#goods-box-code').val(boxCode);
            $('#sort-act-weight').val("");

            //货箱物品总重量
            const totalWeight = data.totalWeight;
            //响应的货箱编号和称重
            //wcs单位为g
            // const sortWeight = data.data.TotalWeight/1000;
            const rows = $('#sort-spu-table').bootstrapTable('getSelections');
            if (rows.length > 0) {
                const row = rows[0];

                let sortWeight = $('#sort-weight').val();

                const spuList = $('#box-list-table').bootstrapTable('filterBy', {spuId: [row.spuId]});
                if (spuList && spuList.length > 0) {
                    const bulk = spuList[0];
                    if (bulk.inBulk && bulk.inBulk === true) {
                        sortWeight = data.sortWeight;
                    }
                }
                console.log("实际称重重量：" + JSON.stringify(data));

                //更新已分拣重量
                // let sortedWeight = 0;

                //可分拣原料重量
                const sortTotalWeight = boxSortWeight(row);
                if (sortTotalWeight <= 0) {
                    checkEmptyGoodsBox(boxCode);
                    return;
                }
                console.log("分拣重量：sortTotalWeight:" + sortTotalWeight);
                // let spuWeight = boxSortWeight(row);
                //非正整数校验
                if (!checkPrice(sortTotalWeight)) {
                    console.log("分拣称重响应重量异常：" + JSON.stringify(sortTotalWeight));
                    // const param = {boxCode: boxCode};
                    // selectBoxDetailByBoxCode(param);
                    checkEmptyGoodsBox(boxCode);
                    return;
                }

                //分拣重量,num.toFixed(2)
                const weight = parseFloat(sortTotalWeight - sortWeight).toFixed(2);
                console.log("剩余weight:" + weight);
                let sortIds = new Array();
                sortIds.push(row.id);
                const param = {sortIds: sortIds, boxCode: boxCode, packId: row.packId};
                console.log("row===" + JSON.stringify(row));
                let sortQuantityInfo = 1;
                //todo 称重响应后在更新，目前先在这更新
                if (weight < 0) {
                    console.log("1111111111111111111");
                    //已分拣重量(重量少于订单需要的重量)
                    param["sortWeight"] = sortTotalWeight;
                    param["bigProduct"] = 0;
                    param["weight"] = row.weight;
                    param["quantity"] = row.quantity;
                    param["standard"] = row.standard;
                    // $('#sort-weight').val(sortTotalWeight);
                    const inErrInfo = updateSortTaskDetail(param);
                    //不在误差范围内，则更新页面
                    if (!inErrInfo.inErr) {
                        $('#total-weight').val("");
                        //分拣重置缺少重量
                        $('#sort-spu-table').bootstrapTable('updateByUniqueId', {
                            id: row.id,
                            row: {
                                sortWeight: row.sortWeight + sortTotalWeight
                            }
                        });

                        //订单重置缺少重量
                        //更新到右边
                        const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
                        if (orderRow) {
                            $('#sort-table').bootstrapTable('updateByUniqueId', {
                                id: row.id,
                                row: {
                                    remainingWeight: Math.abs(weight).toFixed(2),
                                    packId: row.packId
                                }
                            });
                        }
                    } else if (inErrInfo.msg) {
                        BootstrapDialog.alert(inErrInfo.msg);
                    }
                    // checkEmptyGoodsBox(boxCode);
                } else {
                    console.log("22222222222222222222");
                    //货箱入库
                    param["sortWeight"] = sortWeight;
                    param["bigProduct"] = 0;
                    param["weight"] = row.weight;
                    param["quantity"] = row.quantity;
                    param["standard"] = row.standard;
                    // $('#sort-weight').val(sortWeight);
                    //已分拣重量
                    const inErrInfo = updateSortTaskDetail(param);
                    //不在误差范围内，则更新页面
                    if (!inErrInfo.inErr) {
                        if (inErrInfo.quantity) {
                            sortQuantityInfo = inErrInfo.quantity;
                        }
                        //若是有已分拣数量，则减去已分拣数量
                        const num = row.quantity - row.sortQuantity;
                        if (num == 1) {
                            //单份
                            //称重完毕，数量拿完，则重新初始化当前箱子需要分拣的原料列表
                            $('#sort-spu-table').bootstrapTable('removeByUniqueId', row.id);
                            const dataInfo = $('#sort-spu-table').bootstrapTable('getData');
                            if (dataInfo && dataInfo.length > 0) {
                                $('#sort-table').bootstrapTable('checkBy', {field: 'id', values: [row.id]});
                                sortSpuTable(dataInfo, sortTotalWeight, null, true);
                            }
                            // $("#sort-spu-table").bootstrapTable("load", sortDetailList);
                        } else if (num > 1) {
                            $('#sort-table').bootstrapTable('checkBy', {field: 'id', values: [row.id]});
                            $('#sort-spu-table').bootstrapTable('updateByUniqueId', {
                                id: row.id,
                                row: {
                                    sortQuantity: row.sortQuantity + sortQuantityInfo
                                }
                            });
                        }

                        //分拣订单的已分拣数量加1
                        const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
                        if (orderRow) {
                            $('#sort-table').bootstrapTable('updateByUniqueId', {
                                id: orderRow.id,
                                row: {
                                    sortQuantity: orderRow.sortQuantity + sortQuantityInfo,
                                    packId: row.packId
                                }
                            });
                        }
                    } else if (inErrInfo.msg) {
                        BootstrapDialog.alert(inErrInfo.msg);
                    }
                }
                //招商演示用，图片以supId.jpg的形式放到/page/img/下
                // $('#spu-img').attr('src','/page/img/'+row.spuId+'.jpg');
            } else {
                $('#spu-img').attr('src', '/page/img/backgroud.jpg');
            }

            /**校验货箱是否可入库**/
            /*const list = $('#sort-spu-table').bootstrapTable('getData');
            if (list && list.length <= 0) {
                //todo 校验箱子有没其他当前要分拣的原料
                //原料箱没有相关产品的原料
                // sortingEntry(ops);
                console.log("检测空箱箱子》》》");
                checkEmptyGoodsBox(boxCode);
            } else if (list && list.length == 1) {
                const tmp = list[0];
                if (!tmp || !tmp.spuName) {
                    console.log("........");
                    checkEmptyGoodsBox(boxCode);
                    return;
                }
            }*/
            $('#check-weight').show();
        } else {
            if (data.seatId) {
                $('#warehouse-number').text(data.seatId);
            }

            $('#spu-box-code').text(data.boxCode);
            $('#ware-box-code').val(data.boxCode);
            $('#goods-box-code').val(data.boxCode);
            console.log("data.totalWeight:" + data.totalWeight + ";data.actWeight：" + data.actWeight);
            if (data.totalWeight && data.actWeight) {
                //或者之后改成颜色，货箱实际称重重量一个颜色，货箱应剩余物品总重量一个颜色
                BootstrapDialog.alert(data.msg + "；货箱实际称重重量" + data.totalWeight + "；货箱应剩余物品总重量：" + data.actWeight);
            } else if (data.actWeight == 0) {
                //或者之后改成颜色，货箱实际称重重量一个颜色，货箱应剩余物品总重量一个颜色
                BootstrapDialog.alert(data.msg + "；货箱实际称重重量" + data.totalWeight + "；货箱应剩余物品总重量：" + data.actWeight);
            } else {
                BootstrapDialog.alert(data.msg);
            }
            $('#check-weight').show();
        }
        Cookies.remove('checkWeight');
    }
}

function storageDoneCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (!cancel) {
        const obj = data.data;
        if (obj.code == 0) {
        } else {
        }
    }
}

//货箱离开缓存位
function leaveBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
            //按wcs按钮分拣入库，则获取货箱全部可分拣的重量，更新分拣任务
            /*if (obj.upByButton && obj.upByButton == true) {
                const rows = $('#sort-spu-table').bootstrapTable('getData');
                if (rows.length > 0) {
                    let sortIds = new Array();
                    let sortTotalWeight = 0;
                    let boxWeight = 0;
                    for (let i = 0; i < rows.length; i++) {
                        const row = rows[i];
                        const sortWeight = parseFloat((row.quantity - row.sortQuantity) * row.weight).toFixed(2);
                        sortTotalWeight = parseFloat(sortTotalWeight + sortWeight).toFixed(2);
                        //当前货箱可分拣的spu重量
                        const totalWeight = boxSortWeight(row);
                        boxWeight = parseFloat(boxWeight + totalWeight).toFixed(2);
                        sortIds.push(row.id);
                    }
                    //货箱需分拣物品总重量-需分拣物品总重量
                    console.log("boxCode=" + obj.boxCode + "；重量计算：boxWeight=" + boxWeight + ";sortTotalWeight=" + sortTotalWeight);
                    const weight = parseFloat(boxWeight - sortTotalWeight).toFixed(2);
                    const param = {sortIds: sortIds, boxCode: obj.boxCode};
                    if (weight < 0) {
                        $('#total-weight').val(boxWeight);
                        param["sortWeight"] = boxWeight;
                    } else {
                        param["sortWeight"] = sortTotalWeight;
                        $('#total-weight').val(sortTotalWeight);
                    }
                    updateSortTaskDetail(param);
                }
            } else {
                initSortTable(null, null);
            }*/
            // initSortTable(null, null);
            $('#spu-box-code').text("");
            $('#sort-weight').val("");
            $('#sort-act-weight').val("");
            $('#sort-spu-table').bootstrapTable('destroy');
            $('#box-list-table').bootstrapTable('destroy');
            $('#warehouse-number').text("");
            Cookies.remove('boxCode');
            //货箱离开货位，查询其他仓库有没继续分拣的箱子
            selectResponseFromWcs("inBufferPos", $("#client-id").val(), 1, false, inBufferPosCallBack);
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//到达缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        console.log("无缓存数据");
        return;
    }
    console.log("到达缓存位：" + JSON.stringify(data));
    if (!cancel) {
        const obj = data.data;
        if (obj.code == 1) {
            delResponseFromWcs(data, opt);
            BootstrapDialog.alert(obj.msg);
            $('#check-weight').show();
        } else {
            //货箱详情列表
            // const list = obj.data.list;
            const box = obj.data.goodsBox;
            $('#box-type').val(box.boxType);
            /*if (box.actTemperatureCode) {
                $('#temperatureZoneCode').val(box.actTemperatureCode);
            }*/
            //wcs每个周期同一个topic单个依次发送
            //效率够的情况下，暂时不考虑后台循环
            const opt = {boxCode: obj.boxCode};
            selectBoxDetailByBoxCode(opt);

            console.log("展示的货箱编号：" + obj.boxCode);
            //展示货箱编号
            $('#spu-box-code').text(obj.boxCode);
            $('#ware-box-code').val(obj.boxCode);
            $('#goods-box-code').val(obj.boxCode);
            $('#warehouse-number').text(obj.seatId);
            $('#check-weight').show();
        }
    }
}

//分拣称重socketIo响应
function electronicWeightCallBack(data) {
    console.log("称重数据返回：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.weight) {
            sortWeightInfo("sort-spu-table", sortWeightId, sortTyp, 0, vc, 0);
        } else {
            console.log("分拣/报损称重异常：" + data);
        }
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
        }
    }
}

function boxListTable(data) {
    $('#box-list-table').bootstrapTable('destroy');
    $('#box-list-table').bootstrapTable({
        data: data,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        singleSelect: true,
        rowStyle: rowStyle,
        columns: [{
            field: 'weight',
            align: 'left',
            title: '重量'
        }]
    });
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        //分拣空箱出库
        /* if (obj.processType == 0 && obj.processState == 7) {
             //空箱出库成功，则需要把inBufferPos第一个删掉
             const opt = {type: 'inBufferPos', clientId: $('#client-id').val(), processType: 1};
             delResponseFromWcs(null, opt);
         }*/
        console.log("wcs_to_wms:" + JSON.stringify(data));
        const boxCode = obj.boxCode;
        // $('#spu-box-code').text(boxCode);
        // $('#ware-box-code').val(boxCode);
        // $('#goods-box-code').val(boxCode);
        if (obj.code == 0) {

            if (obj.processType == 3 && $('#spu-box-code').val() && $('#spu-box-code').text("") == boxCode) {
                $('#spu-box-code').text("");
                $('#warehouse-number').text("");
                $('#check-weight').hide();
            }
            //分拣称重过程中，wcs_to_wm 的topic响应，不展示称重按钮
            if (!Cookies.get("checkWeight")) {
                //存在多次响应，如入库时会有已到消息队列响应，以及入库称重响应，到消息队列响应，会弹出一次无用按钮延时试试
                $('#check-weight').show();
            }

            // $('#spu-box-code').text("");
            // $('#sort-weight').val("");
            // $('#sort-table').bootstrapTable('refresh');
            //todo web接收到响应，发送事件清除redis
        } else {
            $('#check-weight').show();
            if (obj.seatId) {
                $('#warehouse-number').text(obj.seatId);
            }

            $('#spu-box-code').text(obj.boxCode);
            $('#ware-box-code').val(obj.boxCode);
            $('#goods-box-code').val(obj.boxCode);
            Cookies.remove('boxCode');
            //货箱详情列表
            // const list = obj.data.list;
            $('#spu-box-code').text(boxCode);
            console.log("obj.totalWeight:" + obj.totalWeight + ";obj.actWeight：" + obj.actWeight);
            if (obj.totalWeight && obj.actWeight) {
                //或者之后改成颜色，货箱实际称重重量一个颜色，货箱应剩余物品总重量一个颜色
                BootstrapDialog.alert(obj.msg + "；货箱实际称重重量" + obj.totalWeight + "；货箱应剩余物品总重量：" + obj.actWeight);
            } else if (obj.actWeight == 0) {
                //或者之后改成颜色，货箱实际称重重量一个颜色，货箱应剩余物品总重量一个颜色
                BootstrapDialog.alert(obj.msg + "；货箱实际称重重量" + obj.totalWeight + "；货箱应剩余物品总重量：" + obj.actWeight);
            } else {
                BootstrapDialog.alert(obj.msg);
            }
        }
    }
}

function send(obj, onEvent) {
    if (socket.connected) {
        socket.emit(onEvent, obj);//{msgContent: data}是一个json对象,到了服务端会反序列化
    } else {
        console.log("socketIo未连接");
    }
}

//分拣是否结束，校验，结束则更改分拣状态
function sortDone() {
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/sort/sortDone",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                $('#check-weight').show();
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#check-weight').show();
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//称重
function checkWeight(data) {
    const boxCode = $('#spu-box-code').text();
    if (!boxCode) {
        $('#check-weight').show();
        return;
    }
    const list = $('#sort-spu-table').bootstrapTable('getData');

    console.log("称重list：" + JSON.stringify(list));

    /*let boxWeight = $('#total-weight').val();
    if (!checkPrice(boxWeight)) {
        console.log("价格不符" + boxWeight);
        $('#check-weight').show();
        return;
    }*/

    if (list.length <= 0) {
        //todo 校验箱子有没其他当前要分拣的原料
        //原料箱没有相关产品的原料
        console.log("........");
        checkEmptyGoodsBox(boxCode);
        $('#check-weight').show();
        return;
    } else {
        console.log("称重list111：" + JSON.stringify(list[0]));
        const tmp = list[0];
        if (!tmp || !tmp.spuName) {
            console.log("111........");
            checkEmptyGoodsBox(boxCode);
            $('#check-weight').show();
            return;
        }
    }

    /*console.log(">>>>>>>>boxWeight:" + boxWeight);
    if (parseFloat(boxWeight).toFixed(2) == 0.00) {
        //todo 当箱子原料重量为0
        //原料箱上架
        checkEmptyGoodsBox(boxCode);
        $('#check-weight').show();
        return;
    }*/
    // num.toFixed(2)
    let sortWeight = $('#sort-weight').val();

    //获取选中行
    const rows = $('#sort-spu-table').bootstrapTable('getSelections');
    console.log("选中的行2：" + JSON.stringify(rows));
    if (rows.length > 0) {
        //非正整数校验
        if (!checkPrice(sortWeight)) {
            sortWeight = 0;
        }
        const sortingSpu = rows[0];

        //称重重量，小于每份销售重量的一半，则称重提示
        if ((sortWeight - (parseFloat(sortingSpu.weight) / 2).toFixed(2)) < 0) {
            BootstrapDialog.confirm({
                title: '信息提示',
                message: '当前称重重量为：' + sortWeight + 'g，小于分拣重量。是否继续称重？',
                btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                btnOKLabel: '确定', // <-- Default value is 'OK',
                size: BootstrapDialog.SIZE_NORMAL,
                callback: function (resultConfirm) {
                    if (resultConfirm) {
                        checkWeightInfo(sortingSpu, boxCode, sortWeight);
                    }
                }
            });
        } else {
            checkWeightInfo(sortingSpu, boxCode, sortWeight);
        }
    } else {
        $('#check-weight').show();
        BootstrapDialog.alert("请选中货箱内需要分拣的原料！");
    }
}

function checkWeightInfo(sortingSpu, boxCode, sortWeight) {

    let spuSortWeight = boxSortWeight(sortingSpu);
    if (spuSortWeight <= 0) {
        checkEmptyGoodsBox(boxCode);
        return;
    }
    console.log("可分拣重量：" + spuSortWeight);
    console.log("此次分拣重量：" + sortWeight);
    let weight = parseFloat(spuSortWeight - sortWeight).toFixed(2);
    console.log("weight:" + weight);
    if (!checkPrice(weight)) {
        weight = 0;
    }
    if (weight < 0) {
        //称重
        $('#total-weight').val(sortWeight);
    } else {
        //货箱入库
        $('#total-weight').val(weight);
    }

    if (weight == 0.00 && sortWeight == 0) {
        //报损，提示重量不符，取消提示再称重后
        checkEmptyGoodsBox(boxCode);
    } else {
        Cookies.set("checkWeight", true);
        $('#frm-loss-button').attr("disabled", true);
        $('#sort-act-weight').val(sortWeight);
        let ops = $("#form-param").serializeJSON();
        $('#spu-box-code').text("");
        ops['upOrDownPolicy']['spuId'] = sortingSpu.spuId;
        ops['upOrDownPolicy']['skuCode'] = sortingSpu.skuCode;
        ops['upOrDownPolicy']['specCode'] = sortingSpu.specCode;
        ops['upOrDownPolicy']['volume'] = sortingSpu.volume;
        $('#check-weight').hide();
        console.log("执行分拣称重：" + JSON.stringify(ops));
        $.ajax({
            type: "POST",
            url: "/wcs/sortingWeight",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(ops),
            dataType: "json",
            success: function (data) {
                console.log("sortingWeight:" + JSON.stringify(data));
                if (data.code == 0) {
                } else {
                    Cookies.remove('checkWeight');
                    //货箱离开货位，查询其他仓库有没继续分拣的箱子
                    selectResponseFromWcs("inBufferPos", $("#client-id").val(), 1, false, inBufferPosCallBack);
                    if (data.code != 500) {
                        BootstrapDialog.alert(data.msg);
                    }
                    $('#check-weight').show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#spu-box-code').text($('#goods-box-code').val());
                $('#check-weight').show();
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                    }
                }
            }
        });
    }
}

function boxSortWeight(sortingSpu) {
    //当前货箱可分拣的spu重量
    let spuSortWeight = 0;
    const boxList = $('#box-list-table').bootstrapTable('getData');
    console.log("需分拣信息：" + JSON.stringify(sortingSpu));
    console.log("货箱详情信息：" + JSON.stringify(boxList));
    //获取当前货箱内，需要分拣的spu重量
    if (boxList && boxList.length > 0) {
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            if (sortingSpu.spuId === boxDetail.spuId && sortingSpu.skuCode === boxDetail.skuCode) {
                spuSortWeight = spuSortWeight + boxDetail.weight;
            }
        }
    }
    return parseFloat(spuSortWeight).toFixed(2);
}

//根据订单获取的加工任务列表
function initSortTable(opt, list) {
    $('#sort-table').bootstrapTable('destroy');
    $('#sort-table').bootstrapTable({
        url: '/wcs/sort/sortingTask',        // 表格数据来源
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        rowStyle: rowStyle,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#form-param").serializeJSON();
            /*temp["rows"] = params.limit;                        //页面大小
            temp["page"] = (params.offset / params.limit) + 1;  //页码
            temp["sort"] = params.sort;                         //排序列名
            temp["sortOrder"] = params.order;      */             //排位命令（desc，asc）
            // console.log(JSON.stringify(temp));
            return temp;
        },
        onLoadSuccess: function (data) {
            if (data.code == 0) {
                console.log("6666666666666666" + JSON.stringify(list));
                const sortDetailList = data.data.sortDetailList;
                console.log("777777777777" + JSON.stringify(sortDetailList))
                if (sortDetailList && sortDetailList.length > 0) {
                    //分拣任务列表
                    $("#sort-table").bootstrapTable("load", sortDetailList);

                    if (opt && list) {
                        console.log("-----------是否有效之有效");
                        initDate(opt, list, sortDetailList);
                    } else {
                        console.log("============是否有效之无效");
                    }
                } else {
                    const boxCode = $('#spu-box-code').text();
                    //opt = null && list == null 为inBufferPosCallBack无数据
                    /*if (boxCode && opt != null && list != null) {
                        console.log("8888888888888");
                        checkWeight();
                    }*/
                    if (boxCode) {
                        checkEmptyGoodsBox(boxCode);
                    } else if (opt != null) {
                        checkEmptyGoodsBox(opt.boxCode);
                    }
                    console.log("99999999999999999,boxCode:" + boxCode + ";opt:" + JSON.stringify(opt));
                }
            }
        },
        columns: [
            {
                checkbox: true,
                formatter: function (value, row, index) {
                    if (row.weight * row.quantity - row.sortWeight == 0) {
                        return {checked: true, disabled: true};
                    } else {
                        return {disabled: true};
                    }
                    /*return {
                        disabled : true,//设置是否可用
                        checked : true//设置选中
                    };*/
                }
            }, {
                field: 'spuName',
                align: 'left',
                title: '名称'
            }, {
                field: 'shelfLocation',
                title: '货位'
            }, {
                field: 'quantity',
                title: '数量'
            }, {
                field: 'sortQuantity',
                title: '已分拣数量'
            }, {
                field: 'weight',
                title: '每份重量',
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "background-color": "#007AF5",
                            "font-size": '16px;',
                            "font-weight": "bold",
                            "color": "#FFFFFF"
                        }
                    };
                },
            }, {
                field: "remainingWeight",
                title: "缺少重量",
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "background-color": "#F57A00",
                            "font-size": '16px;',
                            "font-weight": "bold",
                            "color": "#FFFFFF"
                        }
                    };
                },
                formatter: function (value, row, index) {
                    if (value) {
                        return value;
                    } else {
                        if (row.weight && row.sortWeight && row.sortWeight > 0) {
                            return (row.weight * row.quantity - row.sortWeight).toFixed(2);
                        }
                    }
                }
            }, {
                field: 'unit',
                title: '单位'
            }, {
                field: 'spuId',
                title: '原料',
                visible: false
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                valign: 'middle',
                formatter: actionFormatter,
            }]
    });

}

//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    // result += '<a href="javascript:;" class="btn btn-xs green" onclick="outOfStock(\'' + row.id + '\')" title="缺货"><span class="glyphicon glyphicon-pencil"></span></a>';
    result += '<button type="button" class="btn btn-primary" onclick="outOfStock(\'' + row.id + '\')">缺货</button>';
    return result;
}

//样式
function rowStyle(row, index) {
    return {css: {"font-size": '16px;', "font-weight": "bold", "font-family": 'Microsoft YaHei'}};
}

//缺货
function outOfStock(sortDetailId) {
    if (!sortDetailId) {
        return;
    }
    const sortDetail = $('#sort-table').bootstrapTable('getRowByUniqueId', sortDetailId);
    if (sortDetail) {
        BootstrapDialog.confirm({
            title: '信息提示',
            message: sortDetail.spuName + '是否确定作缺货处理?',
            btnCancelLabel: '取消', // <-- Default value is 'Cancel',
            btnOKLabel: '确定', // <-- Default value is 'OK',
            size: BootstrapDialog.SIZE_NORMAL,
            callback: function (result) {
                if (result) {
                    sortDetail.status = 4;
                    console.log("sortDetail:" + JSON.stringify(sortDetail));
                    $.ajax({
                        type: "POST",
                        url: "/wcs/sort/detail/updateStatusById",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(sortDetail),
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 0) {
                                $('#sort-table').bootstrapTable('removeByUniqueId', sortDetail.id);
                            } else {
                                BootstrapDialog.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            if (XMLHttpRequest.responseJSON) {
                                if (XMLHttpRequest.responseJSON.msg) {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                                } else {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                                }
                            }
                        }
                    });
                }
            }
        });
    }
}

function sortSpuTable(data, boxWeight, spuWeightMap, checked) {
    $('#sort-spu-table').bootstrapTable('destroy');
    $('#sort-spu-table').bootstrapTable({
        data: data,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        singleSelect: true,
        onCheck: function (row, $element) {
            console.log("选中的行3：" + JSON.stringify(row));
            //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
            const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
            if (orderRow) {
                $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                insertRow(orderRow, 'sort-table', true);
            }
        },
        rowStyle: rowStyle,
        columns: [
            {
                checkbox: true,
                formatter: function (value, row, index) {
                    if (index === 0) {
                        if (!checked) {
                            //初始化，未选中行时处理，只取货箱内相同品类的总重量
                            boxWeight = spuWeightMap.get(row.spuId);
                        }
                        if (!checkPrice(boxWeight)) {
                            return;
                        }
                        console.log("spuWeightMap:" + JSON.stringify(spuWeightMap));
                        //缺少重量，则下个箱子，称重的是缺少重量的部分，不缺少，则称的是每份重量
                        boxWeight = parseFloat(boxWeight).toFixed(0);
                        console.log("boxWeight:" + boxWeight + ";rowWeight:" + row.weight);
                        const totalSortWeight = (row.weight * (row.quantity - row.sortQuantity)).toFixed(0);
                        console.log("totalSortWeight" + totalSortWeight);
                        if (Number(boxWeight) >= Number(totalSortWeight)) {
                            $('#sort-weight').val(totalSortWeight);
                        } else {
                            $('#sort-weight').val(boxWeight);
                        }

                        //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
                        const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
                        if (orderRow) {
                            $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                            insertRow(orderRow, 'sort-table', true);
                        }

                        /* if (row.weight && row.sortWeight && row.sortWeight > 0) {
                             const weight = (row.weight * row.quantity - row.sortWeight).toFixed(2);
                             //防止weight为负数
                             if (weight > 0) {
                                 console.log(">>>>>>>>>>>>>>>>1" + weight);
                                 $('#sort-weight').val(weight);
                             } else {
                                 console.log(">>>>>>>>>>>>>>>>2" + row.weight);
                                 $('#sort-weight').val(row.weight);
                             }

                         } else {
                             console.log(">>>>>>>>>>>>>>>>3" + row.weight);
                             $('#sort-weight').val(row.weight);
                         }*/
                        return {checked: true};
                    }
                }
            }, {
                field: 'packId',
                align: 'left',
                title: '包装袋',
                // events: onclickEvent,
                formatter: packsToSelect
            }, {
                field: 'spuName',
                align: 'left',
                title: '名称'
            }, {
                field: 'quantity',
                title: '数量',
                formatter: function (value, row, index) {
                    return value - row.sortQuantity;
                }
            }, {
                field: 'weight',
                title: '每份重量'
            }, {
                field: "remainingWeight",
                title: "缺少重量",
                formatter: function (value, row, index) {
                    if (row.weight && row.sortWeight && row.sortWeight > 0) {
                        if (!checked) {
                            //初始化，未选中行时处理，只取货箱内相同品类的总重量
                            boxWeight = spuWeightMap.get(row.spuId);
                        }
                        let weight = (row.weight * row.quantity - row.sortWeight).toFixed(0);
                        console.log("id:" + row.id + ";weight1:" + weight + "boxWeight:" + boxWeight);
                        weight = (weight - boxWeight).toFixed(0);
                        console.log("weight1:" + weight + "boxWeight:" + boxWeight);
                        //防止weight为负数
                        if (weight > 0) {
                            return (row.weight - boxWeight).toFixed(0);
                        } else {
                            /*console.log("0000" + row.checked);
                            const reWeight = (row.weight * row.quantity - row.sortWeight).toFixed(2);
                            console.log("称重完成或货箱到位的分拣重量：" + reWeight);
                            $('#sort-weight').val(reWeight);*/
                            return 0;
                        }
                    }
                }
            }, {
                field: 'unit',
                title: '单位'
            }, {
                field: 'spuId',
                title: '原料',
                visible: false
            }]
    });

    const rows = $('#sort-spu-table').bootstrapTable('getSelections');
    console.log("选中的行1：" + JSON.stringify(rows));
    if (rows.length > 0) {
        const row = rows[0];
        //招商演示用，图片以supId.jpg的形式放到/page/img/下
        console.log("00000000000000:" + JSON.stringify(row))
        $('#spu-img').attr('src', row.imgUrl);
        if (row.weight && row.sortWeight && row.sortWeight >= 0) {
            if (!checked) {
                //初始化，未选中行时处理，只取货箱内相同品类的总重量
                boxWeight = spuWeightMap.get(row.spuId);
            }
            const spuList = $('#box-list-table').bootstrapTable('filterBy', {spuId: [row.spuId]});
            if (spuList && spuList.length > 0) {
                const bulk = spuList[0];
                if (!bulk.inBulk) {
                    // $('#sort-weight').attr("disabled", true);
                }
            }
            let weight = (row.weight * (row.quantity - row.sortQuantity)).toFixed(0);
            console.log("checkedId:" + row.id + ";boxWeight:" + boxWeight + ";weight:" + weight);
            const weightCheck = (weight - boxWeight).toFixed(0);
            //防止weight为负数
            if (weightCheck > 0) {
                $('#sort-weight').val(boxWeight);
            } else {
                $('#sort-weight').val(weight);
            }
        }
    }
    // $('#sort-weight').focus();
}

//包装袋选中事件
window.onclickEvent = {
    'change .pack-select': function (e, value, row, index) {
        if (!value) {
            value = e.currentTarget.value;
        }
        console.log("选中的包装的值：" + value);
        $('#sort-spu-table').bootstrapTable('updateCell', {
            index: index,
            field: 'packId',
            value: value
        })
    }
}

function entry(obj) {
    if (!socket.connected) {
        BootstrapDialog.alert("socket未连接，请稍后！");
        return;
    }
    if (!$('#spu-box-code').text()) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }
    $('#goods-box-code').val($('#ware-box-code').val());
    let ops = $("#form-param").serializeJSON();

    if (obj) {
        $("#sort-box-up").addClass("hidden");
        const boxCode = $("#box-code").text();
        if (boxCode == "" || boxCode.length <= 0) {
            BootstrapDialog.show({
                size: BootstrapDialog.SIZE_NORMAL,
                message: "请鼠标放入左下方称重入输入框，然后扫描货箱编号入库",
                closable: false,
                buttons: [{
                    label: '取消',
                    action: function (dialogItself) {
                        dialogItself.close();
                    }
                }, {
                    label: '确定',
                    cssClass: 'btn-primary',
                    action: function (dialog) {
                        const value = dialog.getModalBody().find('#box-code-entry').val();
                        BootstrapDialog.alert(value);
                        dialog.close();
                    }
                }]
            });
            $("#sort-weight").focus();
            return;
        }
        $('#spu-box-code').text("");
        //订单箱入库
        $.ajax({
            type: "POST",
            url: "/wcs/sortingOrderEntry",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(ops),
            dataType: "json",
            success: function (data) {
                console.log(JSON.stringify(data));
                if (data.code == 0) {

                } else {
                    $('#spu-box-code').text($('#goods-box-code').val());
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#spu-box-code').text($('#goods-box-code').val());
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                    }
                }
            }
        });
    } else {

        /**空箱出库**/
        BootstrapDialog.confirm({
            title: '信息提示',
            message: '是否空箱出库?',
            btnCancelLabel: '取消', // <-- Default value is 'Cancel',
            btnOKLabel: '确定', // <-- Default value is 'OK',
            callback: function (result) {
                // result will be true if button was click, while it will be false if users close the dialog directly.
                if (result) {
                    $('#spu-box-code').text("");
                    $.ajax({
                        type: "POST",
                        url: "/wcs/notEntryEmptyBox",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(ops),
                        dataType: "json",
                        success: function (data) {
                            console.log(data);
                            if (data.code == 0) {
                                const opt = {type: 'inBufferPos', clientId: $('#client-id').val(), processType: 1};
                                delResponseFromWcs(null, opt);
                            } else {
                                $('#spu-box-code').text($('#goods-box-code').val());
                                BootstrapDialog.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $('#spu-box-code').text($('#goods-box-code').val());
                            if (XMLHttpRequest.responseJSON) {
                                if (XMLHttpRequest.responseJSON.msg) {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                                } else {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                                }
                            }
                        }
                    });
                }
            }
        });
    }
}

//强制入库
function entryForce() {
    if (!$('#spu-box-code').text()) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }

    BootstrapDialog.confirm({
        title: '信息提示',
        message: '若未分拣完，强制入库将不会出库分拣货箱，是否强制入库?',
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            // result will be true if button was click, while it will be false if users close the dialog directly.
            if (!result) {
                return;
            }
            $('#spu-box-code').text("");
            //材料箱
            const ops = $("#form-param").serializeJSON();
            //原料箱剩余物料
            /*const entry = $('#sort-spu-table').bootstrapTable('getData');
            if (entry && entry.length > 0) {
                ops['list'] = entry;
            }*/
            $.ajax({
                type: "POST",
                url: "/wcs/entryForce",
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(ops),
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    if (data.code == 0) {

                    } else {
                        $('#spu-box-code').text($('#goods-box-code').val());
                        BootstrapDialog.alert(data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $('#spu-box-code').text($('#goods-box-code').val());
                    if (XMLHttpRequest.responseJSON) {
                        if (XMLHttpRequest.responseJSON.msg) {
                            BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                        } else {
                            BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                        }
                    }
                }
            });
        }
    });
}

function demotion() {

    $('#frm-spu-select').html('');
    let html = '';
    html += '<option class="opt-spu-inf"></option>';
    const boxList = $('#box-list-table').bootstrapTable('getData');
    console.log("。。。。。。。。。。。。。。" + JSON.stringify(boxList));
    if (boxList && boxList.length > 0) {
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            if (boxDetail.spuName && boxDetail.id) {
                html += '<option value="' + boxDetail.id + '" class="opt-spu-inf">' + boxDetail.spuName + '</option>';
            }
        }
    }
    $('#frm-spu-select').append(html);
    $('#frm-spu-select').selectpicker('refresh');


    $('#frm-spu-grade-select').html('');
    const opt = {};
    $.ajax({
        type: "POST",
        url: "/wcs/grade/selectList",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    const gradeList = data.data;
                    let spuGradeHtml = '';
                    spuGradeHtml += '<option class="opt-spu-grade-inf"></option>';
                    for (let i = 0; i < gradeList.length; i++) {
                        const spuGrade = gradeList[i];
                        spuGradeHtml += '<option value="' + spuGrade.id + '" class="opt-spu-grade-inf">' + spuGrade.gradeName + '(' + spuGrade.gradeCode + ')' + '</option>';
                    }
                    $('#frm-spu-grade-select').append(spuGradeHtml);
                    $('#frm-spu-grade-select').selectpicker('refresh');
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });

    $('#demotion-standard-select').html('');
    const ops = {};
    $.ajax({
        type: "POST",
        url: "/wcs/grade/standard/selectList",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    const standardList = data.data;
                    let standardHtml = '';
                    // standardHtml += '<option class="opt-spu-grade-inf"></option>';
                    for (let i = 0; i < standardList.length; i++) {
                        const standard = standardList[i];
                        standardHtml += '<option value="' + standard.id + '" class="opt-spu-grade-inf" style="height: 30px;padding-top: 5px;">' + standard.standardName + '(' + standard.standardCode + ')' + '</option>';
                    }
                    $('#demotion-standard-select').append(standardHtml);
                    $('#demotion-standard-select').selectpicker('refresh');
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
    $('#frm-demotion-model').modal({
        keyboard: false
    })
}

//商品降级
function demotionClick() {
    /*if (!$('#spu-box-code').text()) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }*/
    $('#demotion-goods-detail-box-code').val($('#ware-box-code').val());
    const info = $("#form-param").serializeJSON();
    const standardList = new Array();
    $("#demotion-standard-select option:selected").each(function () {
        standardList.push($(this).val());
    });
    if (standardList.length <= 0) {
        BootstrapDialog.alert("请选择降级标准项！");
        return;
    }
    info['standardList'] = standardList;
    $.ajax({
        type: "POST",
        url: "/wcs/demotion",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(info),
        dataType: "json",
        success: function (data) {
            $('#spu-box-code').text($('#goods-box-code').val());
            console.log(data);
            if (data.code == 0) {

            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#spu-box-code').text($('#goods-box-code').val());
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
    /*let htm = "";
    BootstrapDialog.show({
        size: BootstrapDialog.SIZE_NORMAL,
        message: htm,
        buttons: [{
            label: '取消',
            action: function (dialogItself) {
                dialogItself.close();
            }
        }, {
            label: '确定',
            cssClass: 'btn-primary'
        }]
    });*/
}

//原料报损
function frmLose() {
    $('#frm-lose-select').html('');
    let html = '';
    const boxList = $('#box-list-table').bootstrapTable('getData');
    if (boxList && boxList.length > 0) {
        let flag = false;
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            if (boxDetail.spuName && boxDetail.id && boxDetail.weight > 0) {
                if (!flag) {
                    $('#goods-detail-id').val(boxDetail.id);
                }
                flag = true;
                console.log("--------" + JSON.stringify(boxDetail.spuName));
                html += '<option value="' + boxDetail.id + '" class="opt-frm-inf" style="height: 30px;padding-top: 5px;">' + boxDetail.spuName + '(' + boxDetail.spuId + ')' + '&nbsp;&nbsp;/&nbsp;&nbsp;' + boxDetail.weight + '</option>';
            }
        }
    }
    $('#frm-lose-select').append(html);
    $('#frm-lose-select').selectpicker('refresh');
    $('#frm-lose-model').modal({
        keyboard: false
    })
    clearInterval(sortSetInterval);
    sortWeightId = frmSortWeightIdInfo;
    sortTyp = 1;
    sortWeightInfo("sort-spu-table", sortWeightId, sortTyp, 0, null, 0);
}

//原料报损：取消/报损->false/true
function frmLoseClick(cancel) {
    if (cancel) {
        console.log("1111111111111");
        const id = $('#goods-detail-id').val();
        if (!id) {
            BootstrapDialog.alert("请选择报损原料");
            return;
        }
        const frmLoseWeight = $('#frm-lose-weight').val();
        if (!checkPrice(frmLoseWeight)) {
            BootstrapDialog.alert("输入重量格式不符");
            return;
        }
        const orderRow = $('#box-list-table').bootstrapTable('getRowByUniqueId', id);
        console.log("原料：" + JSON.stringify(orderRow));
        if (orderRow) {
            if (frmLoseWeight > orderRow.weight) {
                BootstrapDialog.alert("报损重量大于货箱内原料重量");
                return;
            } else {
                $('#from-lose-goods-detail-box-code').val($('#ware-box-code').val());
                const opt = $("#form-frm-lose").serializeJSON();
                const std = $('#sort-spu-table').bootstrapTable('getData');
                if (Array.isArray(std)) {
                    opt['sortTaskDetails'] = std;
                    console.log('bootstrapTable getData 是一个数组（即list）');
                }
                opt['clientId'] = $('#client-id').val();
                opt['boxCode'] = $('#ware-box-code').val();
                opt['dataType'] = "SHBS";
                opt['type'] = 0;
                opt['bigProduct'] = 0;
                $.ajax({
                    type: "POST",
                    url: "/wcs/box/detail/updateFrmLoseById",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(opt),
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            $('#frm-lose-model').modal('hide');
                            const opt = {boxCode: $('#spu-box-code').text()};
                            selectBoxDetailByBoxCode(opt);
                            if (data.data) {
                                const goodsBoxDetail = data.data;
                                console.log("货箱信息更改前：" + JSON.stringify(orderRow));
                                $('#box-list-table').bootstrapTable('removeByUniqueId', id);
                                orderRow.weight = goodsBoxDetail.weight;
                                /*if (0.00 == orderRow.weight || orderRow.weight == 0) {
                                    $('#sort-weight').val(0);
                                }*/
                                console.log("货箱信息更改后：" + JSON.stringify(orderRow));
                                insertRow(orderRow, 'box-list-table', true);
                            }
                        } else {
                            $('#frm-loss-button').removeAttr("disabled");
                            BootstrapDialog.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $('#spu-box-code').text($('#goods-box-code').val());
                        if (XMLHttpRequest.responseJSON) {
                            if (XMLHttpRequest.responseJSON.msg) {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                            } else {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                            }
                        }
                    }
                });
            }
        } else {
            BootstrapDialog.alert("报损原料信息不存在");
            return;
        }

    } else {
        console.log("2222222222222");
        // $('#frm-lose-model').modal('hide');
        // $('#goods-detail-id').val("");
        // $('#frm-lose-weight').val("");
        // $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);
    }
}

//分拣处理
function updateSortTaskDetail(opt) {
    //误差范围内，不更新页面
    let inErr = false;
    const result = {};
    $.ajax({
        type: "POST",
        url: "/wcs/sort/detail/updateSortWeightById",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            console.log("ppppppppppppp:" + JSON.stringify(data));
            if (data.code == 0) {
                selectBoxDetailByBoxCode(opt);
                if (data.data && data.data.inError) {
                    console.log("ppppp==========");
                    inErr = data.data.inError;
                    result["inErr"] = inErr;
                }
                if (data.data && data.data.quantity) {
                    result["quantity"] = data.data.quantity;
                }
                checkShelfLocation(opt.boxCode);
            } else {
                result["inErr"] = true;
                result["msg"] = data.msg;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
            result["inErr"] = true;
            result["msg"] = "系统异常";
        }
    });
    return result;
}

//查询货箱详情
function selectBoxDetailByBoxCode(opt) {
    $.ajax({
        type: "POST",
        url: "/wcs/box/detail/selectBoxDetailByBoxCode",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.length > 0) {
                        console.log("55555555555555555555" + JSON.stringify(data.data));
                        // initSortTable(opt, data.data);
                        sortTask(opt, data.data);
                    } else {
                        //报损啥的，需重新下个货箱，然后此箱又直接入库
                        //wcs同一topic,只能单个发送，做个延时
                        setTimeout(function () {
                            $('#check-weight').hide();
                            checkEmptyGoodsBox(opt.boxCode);
                            /*const ops = $("#form-param").serializeJSON();
                            emptyEntry(ops);*/
                        }, 500);

                    }

                    /*const sortDetailList = $('#sort-table').bootstrapTable('getData');
                    if (sortDetailList) {
                        let sortList = new Array();
                        const list = data.data;
                        //更新货箱详情
                        boxListTable(list);
                        let totalWeight = 0;
                        let boxWeight = 0;
                        for (let i = 0; i < list.length; i++) {
                            const goodsDetail = list[i];
                            for (let j = 0; j < sortDetailList.length; j++) {
                                const sort = sortDetailList[j];
                                if (goodsDetail.spuId == sort.spuId && (sort.quantity - sort.sortQuantity) > 0) {
                                    sortList.push(sort);
                                    totalWeight = totalWeight + goodsDetail.weight;
                                }
                            }
                            boxWeight = boxWeight + goodsDetail.weight;
                        }
                        $('#total-weight').val(boxWeight);
                        //更新货箱需分拣列表
                        if (sortList && sortList.length > 0) {
                            $('#sort-spu-table').bootstrapTable('destroy');
                            sortSpuTable(sortList, totalWeight);
                        } else {
                            checkEmptyGoodsBox(opt.boxCode);
                        }
                    }*/
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#check-weight').show();
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//查询分拣任务
function sortTask(opt, list) {
    let temp = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/sort/sortingTask",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(temp),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            console.log("6666666" + JSON.stringify(data));
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.sortDetailList.length > 0) {
                        //todo刷新右边分拣任务
                        /*for (let i = 0; i < data.data.sortDetailList.length; i++) {
                            const sortDetail = data.data.sortDetailList[i];
                            //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
                            const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', sortDetail.id);
                            if (orderRow != 'undefined' && !orderRow) {
                                insertRow(orderRow, 'sort-table', true);
                            }
                        }*/
                        initDate(opt, list, data.data.sortDetailList);
                    } else {
                        //报损啥的，需重新下个货箱，然后此箱又直接入库
                        //wcs同一topic,只能单个发送，做个延时
                        setTimeout(function () {
                            checkEmptyGoodsBox(opt.boxCode);
                            /*const ops = $("#form-param").serializeJSON();
                            emptyEntry(ops);*/
                        }, 500);

                    }
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//初始化货箱需分拣数据
function initDate(opt, list, sortDetailList) {
    if (sortDetailList) {
        let sortList = new Array();
        //更新货箱详情
        boxListTable(list);
        let totalWeight = 0;
        let boxWeight = 0;
        console.log("goodsDetail:" + JSON.stringify(list));
        console.log("sortdetail:" + JSON.stringify(sortDetailList));
        const map = new Map();
        const goodsBoxSpuWeight = new Map();
        for (let i = 0; i < list.length; i++) {
            const goodsDetail = list[i];
            for (let j = 0; j < sortDetailList.length; j++) {
                const sort = sortDetailList[j];
                const totalSortWeight = parseFloat(sort.quantity * sort.weight).toFixed(2);
                // if (goodsDetail.spuId == sort.spuId && (totalSortWeight - sort.sortWeight) > 0) {
                if (goodsDetail.spuId === sort.spuId && (sort.quantity - sort.sortQuantity) > 0) {
                    //不用list，防止同一货箱有相同一批spu情况
                    map.set(sort.id, sort);
                    // totalWeight = totalWeight + goodsDetail.weight;
                }
            }
            //货箱同一个品类总重量
            if (goodsBoxSpuWeight.has(goodsDetail.spuId)) {
                const spuWeight = Number(parseFloat(goodsBoxSpuWeight.get(goodsDetail.spuId)).toFixed(0)) + goodsDetail.weight;
                goodsBoxSpuWeight.set(goodsDetail.spuId, spuWeight);
            } else {
                goodsBoxSpuWeight.set(goodsDetail.spuId, parseFloat(goodsDetail.weight).toFixed(2));
            }
            boxWeight = boxWeight + goodsDetail.weight;
        }
        for (const key of map.keys()) {
            sortList.push(map.get(key));
        }
        $('#total-weight').val(parseFloat(boxWeight).toFixed(2));
        console.log("total-weight:" + boxWeight);
        //更新货箱需分拣列表
        console.log("initDate：" + JSON.stringify(goodsBoxSpuWeight));
        if (sortList && sortList.length > 0) {
            sortSpuTable(sortList, 0, goodsBoxSpuWeight, false);
        } else {
            checkEmptyGoodsBox(opt.boxCode);
        }
    }
}

function updateSortList(sortList, boxWeight, spuWeightMap, checked) {
    for (let i = 0; i < sortList.length; i++) {
        const sortDetail = sortList[i];
        let remainingWeight = 0;
        if (sortDetail.weight && sortDetail.sortWeight && sortDetail.sortWeight > 0) {

            //初始化，未选中行时处理，只取货箱内相同品类的总重量
            if (!checked) {
                //初始化，未选中行时处理，只取货箱内相同品类的总重量
                boxWeight = spuWeightMap.get(sortDetail.spuId);
            }
            if (i == 0) {
                if (!checkPrice(boxWeight)) {
                    return;
                }
                //缺少重量，则下个箱子，称重的是缺少重量的部分，不缺少，则称的是每份重量
                boxWeight = parseFloat(boxWeight).toFixed(2);
                if (boxWeight >= sortDetail.weight) {
                    $('#sort-weight').val(sortDetail.weight);
                } else {
                    $('#sort-weight').val(boxWeight);
                }

                //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
                const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
                if (orderRow) {
                    $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                    insertRow(orderRow, 'sort-table', true);
                }
            }

            let weight = (sortDetail.weight * sortDetail.quantity - sortDetail.sortWeight).toFixed(2);
            weight = (weight - boxWeight).toFixed(2);
            //防止weight为负数
            if (weight > 0) {
                remainingWeight = (sortDetail.weight - boxWeight).toFixed(2);
            } else {
                remainingWeight = 0;
            }
        }
        $('#sort-spu-table').bootstrapTable('updateByUniqueId', {
            id: sortDetail.id,
            row: {
                sortWeight: sortDetail.sortWeight,
                quantity: sortDetail.quantity - sortDetail.sortQuantity,
                remainingWeight: remainingWeight
            }
        });
    }
}

//校验原料箱状态，再入库
function checkEmptyGoodsBox(boxCode) {
    // $('#check-weight').hide();
    //刚到达缓存位就上架，到达缓存位状态未更改完成，延时一下
    setTimeout(function () {
        $.ajax({
            type: "POST",
            url: "/wcs/box/checkEmptyGoodsBox",
            contentType: "application/json;charset=UTF-8",
            data: boxCode,
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    if (data.data) {
                        if (data.data.detailList && data.data.detailList.length > 0) {
                            console.log("校验原料箱状态，再入库:" + JSON.stringify(boxCode));
                            $('#ware-box-code').val(boxCode);
                            $('#goods-box-code').val(boxCode);
                            const opt = $("#form-param").serializeJSON();
                            opt['list'] = data.data.detailList;
                            sortingEntry(opt);
                        } else {
                            if ($('#ware-box-code').val() == boxCode) {
                                const ops = $("#form-param").serializeJSON();
                                console.log("空箱入库");
                                emptyEntry(ops);
                            }
                            /*BootstrapDialog.confirm({
                                title: '信息提示',
                                message: '货箱已为空，是否空箱入库?',
                                btnCancelLabel: '出库', // <-- Default value is 'Cancel',
                                btnOKLabel: '入库', // <-- Default value is 'OK',
                                callback: function (result) {
                                    // result will be true if button was click, while it will be false if users close the dialog directly.
                                    if (!result) {
                                        $('#check-weight').show();
                                        return;
                                    }
                                    emptyEntry(ops);
                                }
                            });*/
                        }
                    }
                } else {
                    $('#check-weight').show();
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        XMLHttpRequest.responseJSON.message
                    }
                }
            }
        });
    }, 500);
}

//检查原料箱是否为空箱，再做库位调整
function checkShelfLocation(boxCode) {
    $.ajax({
        type: "POST",
        url: "/wcs/box/checkShelfLocation",
        contentType: "application/json;charset=UTF-8",
        data: boxCode,
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
        }
    });
}

//分拣原料入库
function sortingEntry(opt) {
    if (!$('#spu-box-code').text()) {
        // BootstrapDialog.alert("货箱编号为空");
        return;
    }
    console.log("原料入库:" + JSON.stringify(opt));
    //非空箱
    $.ajax({
        type: "POST",
        url: "/wcs/sortingEntry",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                $('#check-weight').show();
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#check-weight').show();
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
        }
    });
}

//空箱入库
function emptyEntry(ops) {
    if (!$('#spu-box-code').text()) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }
    console.log("空箱入库：" + JSON.stringify(ops));
    //空箱
    $.ajax({
        type: "POST",
        url: "/wcs/emptyEntry",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                $('#check-weight').show();
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    buttons: [{
                        label: '继续入库',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            emptyEntry(ops);
                            dialog.close();
                        }
                    }]
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#check-weight').show();
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
        }
    });
}

//货箱下一个原料 to do
function nextSpuOfGoodsBox() {
    if (goodsBox) {
        const detailList = goodsBox.detailList;
        if (detailList) {
            const list = detailList.shift();
            if (list.length > 0) {
                console.log("货箱下一个原料：" + JSON.stringify(list));
                const data = $('#sort-table').bootstrapTable('getData');
                if (data.length > 0) {
                    for (let i = 0; i < list.length; i++) {
                        const tmp = list[i];
                        for (let j = 0; j < data.length; j++) {
                            if (tmp.spuId == data[i].spuId) {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}

function sortChangeShifts() {
    window.location.href = "../../login";
}


